import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

/**
 * @author wcj
 * @Date 2021/6/8 10:38
 * @Version 1.0
 */
public class Priority {

    private static volatile boolean notStart = true;
    private static volatile boolean notEnd = true;

    /**
     * 不能通过设定线程的优先级去确定线程的执行顺序，从而得到正确的结果
     * 因为操作系统压根不管，并且java线程优先级进和os的优先级也没有一个映射关系
     *
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        ArrayList<Job> jobs = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            int priority = i < 5 ? Thread.MIN_PRIORITY : Thread.MAX_PRIORITY;
            Job job = new Job(priority);
            jobs.add(job);
            Thread thread = new Thread(job, "Thread-" + i);
            thread.setPriority(priority);
            thread.start();
        }
        notStart = false;
        TimeUnit.MILLISECONDS.sleep(10);
        notEnd = false;
        for (Job job : jobs) {
            System.out.println("priority:" + job.priority + ",count:" + job.jobCount);
        }
    }


    /**
     * 这是任务，一定要区分任何和线程
     */
    static class Job implements Runnable {
        private int priority;
        private int jobCount;

        public Job(int priority) {
            this.priority = priority;
        }

        @Override
        public void run() {
            if (notStart) {
                Thread.yield();
            }
            if (notEnd) {
                Thread.yield();
                jobCount++;
            }
        }
    }
}

